//
//  LGSConnectionContext.m
//  LogicSim
//
//  Created by Jeremy Pereira on 20/04/2012.
//  Copyright (c) 2012 Jeremy Pereira. All rights reserved.
//

#import "LGSConnectionContext.h"
#import "LGSNode.h"
#import "LGSError.h"
#import "LGSName.h"

@implementation LGSConnectionContext
{
@private
    NSMutableArray* nodeMaps;
}

-(id) init
{
    self = [super init];
    if (self != nil)
    {
        nodeMaps = [[NSMutableArray alloc] init];
        [self push];
    }
    return self;
}

-(LGSNode*) nodeForName: (LGSName*) nameToSearch
{
    __block LGSNode* ret = nil;
    [nodeMaps enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
    {
        ret = [obj objectForKey: [nameToSearch nameWithoutConnection]];
        if (ret != nil)
        {
            *stop = YES;
        }
    }];
    return ret;
}

-(bool) addNode: (LGSNode*) nodeToAdd error: (NSError* __autoreleasing *) error
{
    bool ret = false;
    LGSName* key = [nodeToAdd name];
    LGSNode* existingObject = [[nodeMaps objectAtIndex: 0] objectForKey: key];
    if (existingObject == nil)
    {
        [[nodeMaps objectAtIndex: 0] setObject: nodeToAdd forKey: key];
        ret = true;
    }
    else 
    {
        if (error != nil)
        {
            NSString* reason 
            	= [NSString stringWithFormat: @"Duplicate node with id %@", key];
            *error = [LGSError deserialisationFailureReason: reason];
        }
    }
    return ret;
}

-(void) push
{
    [nodeMaps addObject: [[NSMutableDictionary alloc] init]];
}

-(void) pop
{
    [nodeMaps removeObjectAtIndex: 0];
}

@end
